import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadLock2 {
    private static int number=0;
    //1.创建锁对象
    private static Lock lock=new ReentrantLock(true);
    static class Counter{
        //循环次数
        private static int MAX_COUNT=1000000;
        //++方法
        public  static void incr(){
            for (int i = 0; i < MAX_COUNT; i++) {
                //2.加锁操作
                lock.lock();
                try{
                    //业务代码
                    number++;
                }finally{
                    //3.释放锁
                    lock.unlock();
                }
            }
        }
        //--方法
        public  static void decr(){
            for (int i = 0; i <MAX_COUNT ; i++) {
                //2.加锁操作
                lock.lock();
                try{
                    //业务代码
                    number--;
                }finally{
                    //3.释放锁
                    lock.unlock();
                }
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        long stime=System.currentTimeMillis();
        Thread t1=new Thread(()->{
            Counter.incr();
        });
        t1.start();

        Thread t2=new Thread(()->{
            Counter.decr();
        });
        t2.start();

        //等待线程执行完成
        t1.join();
        t2.join();
        long etime=System.currentTimeMillis();
        System.out.println("最终的结果是:"+number+"|执行时间:"+(etime-stime));
    }
}
